#!/usr/bin/env node
const fs = require('fs');
const path = require('path');

const args = process.argv.slice(2);
const mode = args[0];        // pre / suf / preview
const dirPath = args[1];     // 目标目录
const fix = args[2] || '';   // 前缀或后缀字符串

function help() {
  console.log(`
批量重命名小工具
用法:
  node zjr.js pre  <目录> <前缀>    加前缀
  node zjr.js suf  <目录> <后缀>    加后缀
  node zjr.js preview pre/suf <目录> <前/后缀>  仅预览
`);
}

if (!mode || !dirPath) {
  help();
  process.exit(0);
}

if (!fs.existsSync(dirPath)) {
  console.error('目录不存在:', dirPath);
  process.exit(1);
}

const files = fs.readdirSync(dirPath)
  .map(f => path.join(dirPath, f))
  .filter(f => fs.statSync(f).isFile());

if (!files.length) {
  console.log('目录下无文件');
  process.exit(0);
}

const doRename = mode !== 'preview';
const isPre = mode === 'pre' || (mode === 'preview' && args[1] === 'pre');

files.forEach(old => {
  const dir = path.dirname(old);
  const ext = path.extname(old);
  const base = path.basename(old, ext);
  const newBase = isPre ? fix + base : base + fix;
  const newName = newBase + ext;
  const newPath = path.join(dir, newName);

  console.log(doRename ? '重命名:' : '预览:', path.basename(old), '→', newName);
  if (doRename) fs.renameSync(old, newPath);
});

console.log(doRename ? '全部完成！' : '预览结束，去掉 preview 再执行即可真正改名');